<template>
  <main class="main-content">
    <div class="breadcrumb">
      <span class="breadcrumb-item">设备管理</span>
      <span class="breadcrumb-separator">/</span>
      <span class="breadcrumb-item active">设备发现池</span>
    </div>

    <div class="card">
      <div class="table-actions-bar">
        <a-space>
          <a-button type="primary" :disabled="!hasSelected" @click="openBatchImportModal">
            批量导入 ({{ selectedRowKeys.length }})
          </a-button> 
          <a-button :disabled="!hasSelected">删除选中</a-button>
        </a-space>
        <a-button @click="fetchDiscoveredDevices(true)">
          <template #icon><ReloadOutlined /></template>
          刷新
        </a-button>
      </div>

      <a-table
        :columns="columns"
        :data-source="discoveredList"
        :loading="loading"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        row-key="id"
        :pagination="pagination"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="record.status === 'PENDING_IMPORT' ? 'processing' : 'success'">
              {{ record.status === 'PENDING_IMPORT' ? '待导入' : '已导入' }}
            </a-tag>
          </template>
        </template>
      </a-table>
    </div>
    
<!-- 批量导入弹窗 -->
    <a-modal 
      title="批量导入设备" 
      v-model:open="importModalVisible" 
      @ok="handleBatchImport"
      :confirm-loading="batchImportLoading"
    >
        <p>将为选中的 <strong>{{ selectedRowKeys.length }}</strong> 台设备设置以下公共信息：</p>
        <a-form layout="vertical" :model="importForm" ref="importFormRef">
          <a-form-item label="安装位置" name="locationId" :rules="[{ required: true, message: '请选择安装位置' }]">
            <a-tree-select
                v-model:value="importForm.locationId"
                style="width: 100%"
                :tree-data="locationTree"
                placeholder="请选择"
                tree-default-expand-all
                :field-names="{ children: 'children', label: 'name', value: 'id' }"
            />
          </a-form-item>
          <a-form-item label="维护责任人">
            <a-input v-model:value="importForm.maintainer" />
          </a-form-item>
        </a-form>
    </a-modal>
  </main>
</template>

<script setup>
import { ref, onMounted, computed, reactive } from 'vue';
import { message } from 'ant-design-vue';
import { ReloadOutlined } from '@ant-design/icons-vue';

import apiClient from '../../api/axios'; // 直接使用 apiClient
import { getDiscoveredDevices, batchImportDevices } from '@/api/deviceDiscovers';
import { getLocationTree } from '@/api/locations';


// --- 表格列定义 ---
const columns = [
  { title: 'IP 地址', dataIndex: 'ipAddress', key: 'ipAddress' },
  { title: '端口', dataIndex: 'port', key: 'port', width: '100px', align: 'center' },
  { title: '设备型号', dataIndex: 'model', key: 'model' },
  { title: '发现时间', dataIndex: 'discoveredAt', key: 'discoveredAt', customRender: ({ text }) => formatDateTime(text) },
  { title: '状态', dataIndex: 'status', key: 'status' },
];

const fetchLocations = async () => {
    try {
        const response = await getLocationTree();
        locationTree.value = response.data;
    } catch (error) {
        message.error("加载位置列表失败");
    }
}

const openBatchImportModal = () => {
  // 打开前先加载位置树数据
  if (locationTree.value.length === 0) {
      fetchLocations();
  }
  importModalVisible.value = true;
};

// 【新增】处理批量导入
const handleBatchImport = async () => {
    try {
        await importFormRef.value.validate(); // 校验表单
        batchImportLoading.value = true;
        
        const payload = {
            discoveredDeviceIds: selectedRowKeys.value,
            locationId: importForm.locationId,
            maintainer: importForm.maintainer
        };
        
        await batchImportDevices(payload);
        
        message.success(`成功导入 ${selectedRowKeys.value.length} 台设备！`);
        importModalVisible.value = false;
        selectedRowKeys.value = []; // 清空选择
        await fetchDiscoveredDevices(true); // 刷新列表

    } catch (error) {
        // 表单校验失败会进入这里
        if(error.errorFields) return; 
        // API 错误
        message.error(error.response?.data?.message || "批量导入失败");
        console.error(error);
    } finally {
        batchImportLoading.value = false;
    }
};

const importFormRef = ref();
const importForm = reactive({
  locationId: null,
  maintainer: '',
});
const locationTree = ref([]);

 
// --- 响应式状态 ---
const loading = ref(false);
const discoveredList = ref([]);
const pagination = reactive({ 
    current: 1, 
    pageSize: 10, 
    total: 0,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条数据`,
});
const selectedRowKeys = ref([]);

const importModalVisible = ref(false);
const batchImportLoading = ref(false);

const hasSelected = computed(() => selectedRowKeys.value.length > 0);

// --- API 调用 ---
const fetchDiscoveredDevices = async (resetPage = false) => {
  if (resetPage) {
    pagination.current = 1;
  }
  loading.value = true;
  selectedRowKeys.value = [];
  try {
    const params = {
      page: pagination.current - 1, // antd 分页从1开始，后端从0开始
      size: pagination.pageSize,
      sort: 'discoveredAt,desc' // 按发现时间降序排序
    };
    // 【核心改造】调用真实的后端接口
    const response = await apiClient.get('/discovered-devices', { params });
    
    discoveredList.value = response.data.content;
    pagination.total = response.data.totalElements;

  } catch (error) {
    message.error("获取发现列表失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// --- 事件处理 ---
const onSelectChange = (keys) => {
  selectedRowKeys.value = keys;
};

const handleTableChange = (pager) => {
  pagination.current = pager.current;
  pagination.pageSize = pager.pageSize;
  fetchDiscoveredDevices();
};

 
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return '-';
  return new Date(dateTimeString).toLocaleString('zh-CN', { hour12: false });
};

// --- 生命周期钩子 ---
onMounted(() => {
  fetchDiscoveredDevices();
});
</script>

<style scoped>
.table-actions-bar {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
}
</style>